<?php
/*
 *  FireFly theme
 *  (c) 2011, chugylo
 */

require 'insertions.php';

function get_theme_settings() {
    // parse ini-file for user settings
    $firefly_settings = parse_ini_file(get_template_directory() .'/firefly.ini');
    return $firefly_settings;
}

function firefly_init() {
    if (!is_admin()) {
        $settings = get_theme_settings();
        $jquery_cdn = $settings['jquery_cdn'];
        wp_deregister_script('jquery');
        wp_register_script('jquery', $jquery_cdn, array(), '1.6.1');  // jQuery from external CDN
        // main script
        if (debug())
            wp_register_script('firefly-script', get_template_directory_uri() .'/script.js', array('jquery'), '3');
        else  // use minified version
            wp_register_script('firefly-script', get_template_directory_uri() .'/script.min.js', array('jquery'), '3');
        wp_register_script('plusone', 'https://apis.google.com/js/plusone.js');  // Google's +1 button
        wp_enqueue_script('jquery');
        wp_enqueue_script('firefly-script');
        if (!debug()) {  // init social buttons
            wp_enqueue_script('plusone');
        }
        wp_localize_script('firefly-script', 'objectL10n', array(
            'search' => __('Search', 'firefly'),
            'ie_text' => __('Your web-browser ({0}) is not supported by this site. It shows design of web-pages wrong and has a weak security level. Use modern browsers like {1}http://www.mozilla.com/en-US/firefox/new/{2} or {3} instead.', 'firefly'),
            'ie_close' => __('Close [x]', 'firefly'),
            'empty_fields' => __('Required fields (Name, Email and Comment) must be filled!', 'firefly'),
            'valid_email' => __('Not a valid email address!', 'firefly')
        ));

        if (debug())
            wp_register_style('firefly-style', get_template_directory_uri() .'/style.css', array(), '4', 'all');
        else  // use minified version
            wp_register_style('firefly-style', get_template_directory_uri() .'/style.min.css', array(), '4', 'all');
        wp_enqueue_style('firefly-style');
    }
}

function firefly_widgets_init() {
    // Area 1. Primary sidebar
    register_sidebar(array(
        'name' => __('Primary Widget Area', 'firefly'),
        'id' => 'primary-widget-area',
        'description' => __('The primary widget area', 'firefly'),
        'before_widget' => '<div id="%1$s" class="sidebar-box widget-container %2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ));
    // Area 2. First column in footer
    register_sidebar(array(
        'name' => __('Footer Widget Area', 'firefly'),
        'id' => 'footer-widget-area',
        'description' => __('The footer widget area', 'firefly'),
        'before_widget' => '<div id="%1$s" class="footer-column widget-container %2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ));
}
add_action('widgets_init', 'firefly_widgets_init');

class MostCommentedPostsWidget extends WP_Widget {
    // Most Commented Posts widget

    function MostCommentedPostsWidget() {  // constructor
        $widget_ops = array(
            'classname' => 'most-commented-widget',
            'description' => __("List most commented posts.", 'firefly'));
        $control_ops = array('width' => 300, 'height' => 300);
        $this->WP_Widget('most-commented-posts', __('Most Commented Posts', 'firefly'), $widget_ops, $control_ops);
    }

    function _list($instance) {
        extract($instance);
        $settings = get_theme_settings();
        $num = (int) $most_commented_number;
        $most_commented_show_count === 'false' ? $show_count = false : $show_count = true;

        global $wpdb;
        $sql =
            // FIXME: is realy Wordpress generates URL from post_date or maybe from post_date_gmt etc?
            "SELECT post_date, post_title, post_name, comment_count
            FROM $wpdb->posts
            ORDER BY comment_count DESC
            LIMIT $num";
        $result = $wpdb->get_results($sql);
        $array = array();
        foreach ($result as $r) {
            $date = explode(' ', $r->post_date);
            $date = $date[0];
            $year = substr($date, 0, 4);
            $month = substr($date, 5, 2);
            $day = substr($date, 8, 2);
            $url = site_url() ."/$year/$month/$day/$r->post_name/";
            $array[] = array($r->post_title, $url, $r->comment_count);
        }
        $res = '';
        foreach ($array as $a) {
            // $a[0] - title
            // $a[1] - URL
            // $a[2] - comment count
            if ($show_count)
                $res .= sprintf("    <li><a href=\"%s\">%s</a> (%s)</li>\n", $a[1], $a[0], $a[2]);
            else
                $res .= sprintf("    <li><a href=\"%s\">%s</a></li>\n", $a[1], $a[0]);
        }
        return "\n<ul>\n". $res ."\n</ul>\n";
    }

    function widget($args, $instance) {
        extract($args);
        $title = apply_filters('widget_title', $instance['title']);
        ?>
              <?php echo $before_widget; ?>
                  <?php if ($title)
                        echo $before_title . $title . $after_title; ?>
                        <?php echo $this->_list($instance); ?>
              <?php echo $after_widget; ?>
        <?php
    }

    function update($new_instance, $old_instance) {
        $instance = $old_instance;
        $instance['title'] = strip_tags(stripslashes($new_instance['title']));
        $instance['most_commented_number'] = strip_tags(stripslashes($new_instance['most_commented_number']));
        $instance['most_commented_show_count'] = strip_tags(stripslashes($new_instance['most_commented_show_count']));
        return $instance;
    }

    function form($instance) {
        // defaults
        $instance = wp_parse_args((array) $instance, array(
            'title'=>__('Most Commented Posts', 'firefly'),
            'most_commented_number'=>'7',
            'most_commented_show_count'=>'true' /* changing most_commented_show_count default value must be completed in HTML code bellow */));
        $title = esc_attr($instance['title']);
        $most_commented_number = esc_attr($instance['most_commented_number']);
        $most_commented_show_count = esc_attr($instance['most_commented_show_count']);
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'firefly'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
            <label for="<?php echo $this->get_field_id('most_commented_number'); ?>"><?php _e('Elements number:', 'firefly'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('most_commented_number'); ?>" name="<?php echo $this->get_field_name('most_commented_number'); ?>" type="text" value="<?php echo $most_commented_number; ?>" />
            <label for="<?php echo $this->get_field_id('most_commented_show_count'); ?>"><?php _e('Show count:', 'firefly'); ?></label><br />
            <input class="widefat" id="<?php echo $this->get_field_id('most_commented_show_count'); ?>" name="<?php echo $this->get_field_name('most_commented_show_count'); ?>" type="radio" value="true"<?php if ($most_commented_show_count==='true') echo 'checked="checked"'; ?> /><?php _e('Yes', 'firefly'); ?><br />
            <input class="widefat" id="<?php echo $this->get_field_id('most_commented_show_count'); ?>" name="<?php echo $this->get_field_name('most_commented_show_count'); ?>" type="radio" value="false"<?php if ($most_commented_show_count==='false') echo 'checked="checked"'; ?>  /><?php _e('No', 'firefly'); ?>
        </p>
        <?php
    }

} // end class MostCommentedPostsWidget
// register Most Commented Posts widget
add_action('widgets_init', create_function(null, 'register_widget("MostCommentedPostsWidget");'));

class BetterRelatedPostsWidget extends WP_Widget {
    // Widget
    // Integration with Better Related Posts plugin

    function BetterRelatedPostsWidget() {  // constructor
        $widget_ops = array(
            'classname' => 'related-widget',
            'description' => __("List related posts.", 'firefly'));
        $control_ops = array('width' => 300, 'height' => 300);
        $this->WP_Widget('related-posts', __('Better Related Posts', 'firefly'), $widget_ops, $control_ops);
    }

    function widget($args, $instance) {
        extract($args);
        $title = apply_filters('widget_title', $instance['title']);
        ?>
              <?php echo $before_widget; ?>
                  <?php if ($title)
                        echo $before_title . $title . $after_title;
                        if (function_exists('the_related'))
                            the_related();
                        else {
                            echo '<p>';
                            _e('"Better Related Posts" plugin is not found. Install and activate it.', 'firefly');
                            echo '</p>';
                        } ?>
              <?php echo $after_widget; ?>
        <?php
    }

    function update($new_instance, $old_instance) {
        $instance = $old_instance;
        $instance['title'] = strip_tags(stripslashes($new_instance['title']));
        return $instance;
    }

    function form($instance) {
        // defaults
        $instance = wp_parse_args((array) $instance, array('title'=>__('Related Posts', 'firefly')));
        $title = esc_attr($instance['title']);
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'firefly'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
        </p>
        <?php
        if (!is_plugin_active('better-related/better-related.php')) {
            echo '<p>';
            _e('WARNING: "Better Related Posts" plugin looks like not found. If this assumption is not wrong, install and activate it.', 'firefly');
            echo '</p>';
        }
    }

} // end class BetterRelatedPostsWidget
// register Better Related Posts widget
add_action('widgets_init', create_function(null, 'register_widget("BetterRelatedPostsWidget");'));

class AboutAuthorWidget extends WP_Widget {
    // Display information about author accoding to data in the user profile

    function AboutAuthorWidget() {  // constructor
        $widget_ops = array(
            'classname' => 'about-widget',
            'description' => __("Display information about author accoding to data in the user profile.", 'firefly'));
        $control_ops = array('width' => 300, 'height' => 300);
        $this->WP_Widget('about-author', __('About Author', 'firefly'), $widget_ops, $control_ops);
    }

    function widget($args, $instance) {
        extract($args);
        $title = apply_filters('widget_title', $instance['title']);
        echo $before_widget;
        if ($title) echo $before_title . $title . $after_title;

        $userID = get_the_author_meta('ID');
        //$userdata = get_userdata($userID);
        if ($userID != '') :
            echo '<div class="about-author-wraper">';
                // you may edit from here to "//end" to change output totally
                echo get_avatar(get_the_author_meta('user_email'), '80'); ?>
                <?php
                $nickname = get_the_author_meta('nickname');
                $description = get_the_author_meta('description');
                if ($nickname != '') {
                    echo '<p class="about-nickname">';
                    _e($nickname);
                    echo '</p>';
                }
                if ($description != '') {
                    echo '<p class="about-description">';
                    _e($description);
                    echo '</p>';
                }
                else {
                    echo '<p>';
                    printf(__('Author\'s bio may be displayed here. Go to %sthe profile%s and set it.', 'firefly'), '<a href="'.site_url().'/wp-admin/profile.php">', '</a>');
                    echo '</p>';
                } ?>
            </div>
        <?php endif;  //end
        echo $after_widget;
    }

    function update($new_instance, $old_instance) {
        $instance = $old_instance;
        $instance['title'] = strip_tags(stripslashes($new_instance['title']));
        return $instance;
    }

    function form($instance) {
        // defaults
        $instance = wp_parse_args((array) $instance, array('title'=>__('About Author', 'firefly')));
        $title = esc_attr($instance['title']);
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'firefly'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
        </p>
        <?php
    }

} // end class AboutAuthorWidget
// register About Author widget
add_action('widgets_init', create_function(null, 'register_widget("AboutAuthorWidget");'));

function social_buttons($permalink) {
    // print Tweet, Facebook's Like and Google's +1 buttons
    // See also: firefly_init() for init social buttons
    // Common usage: social_button(get_permalink())
    if (!debug()) { // don't make this traffic in debug mode
        wp_enqueue_script('plusone');
        ?>
        <div class="post-social-buttons">
            <span class="twitter-button"><a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="chugylo">Tweet</a></span>
            <span class="facebook-button"><iframe src="http://www.facebook.com/plugins/like.php?href=<?= $permalink; ?>&amp;layout=button_count&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:110px; height:35px;" allowTransparency="true"></iframe></span>
            <span class="plusone-button"><g:plusone size="medium"></g:plusone></span>
        </div>
        <?php
    } // end debug
}

function social_buttons_on_all() {
    // show social buttons anywhere (long time loading page) or
    // on singular pages only (by default)
    // return boolean
    $settings = get_theme_settings();
    return $settings['social_buttons_on_all'];
}

function firefly_tags($input, $separator=', ') {
    // Extended the_tags() function.
    // It consider get_the_tags() output and prints "No tags", "Tag: " or "Tags: ".
    // Common usage: firefly_tags(get_the_tags());
    $number = count($input);
    $title = __('Get all publications tagged as %s', 'firefly');
    if ($number > 1) {
        echo __('Tags: ', 'firefly');
        $array = array();
        foreach ($input as $tag_obj)
            array_push($array, array($tag_obj->name, get_tag_link($tag_obj->term_id)));
        $htmled_tags = array();
        foreach ($array as $a)
            array_push($htmled_tags, sprintf("<a href=\"%s\" title=\"$title\" rel=\"tag\">%s</a>", $a[1], $a[0], $a[0]));
        echo implode($separator, $htmled_tags);
        echo "\n";
    }
    elseif ($number == 1 && $input !== false) {
        echo __('Tag: ', 'firefly') ;
        $tag = current($input);  // index may not be equal to 0 so we get value in such way
            printf("<a href=\"%s\" title=\"$title\" rel=\"tag\">%s</a>\n", get_tag_link($tag->term_id), $tag->name, $tag->name);
    }
    else
        _e('No tags', 'firefly');
}

function firefly_categories($input, $separator=', ') {
    // Extended the_category() function.
    // It consider get_the_category() output and prints "Category: " or "Categories: ".
    // Common usage: firefly_categories(get_the_category());
    $number = count($input);
    $title = __('Get all publications in %s', 'firefly');
    if ($number > 1) {
        echo __('Categories: ', 'firefly');
        $array = array();
        foreach ($input as $cat_obj)
            array_push($array, array($cat_obj->cat_name, get_category_link($cat_obj->cat_ID)));
        $htmled_cats = array();
        foreach ($array as $a)
            array_push($htmled_cats, sprintf("<a href=\"%s\" title=\"$title\" rel=\"category tag\">%s</a>", $a[1], $a[0], $a[0]));
        echo implode($separator, $htmled_cats);
        echo "\n";
    }
    elseif ($number == 1 && $input !== false) {
        echo __('Category: ', 'firefly') ;
        $cat = current($input);  // index may not be equal to 0 so we get value in such way
            printf("<a href=\"%s\" title=\"$title\" rel=\"category tag\">%s</a>\n", get_category_link($cat->cat_ID), $cat->cat_name, $cat->cat_name);
    }
}

function list_pings($comment, $args, $depth) {
    // nice look for pings
    $GLOBALS['comment'] = $comment; ?>
    <li id="comment-<?php comment_ID(); ?>"><?php comment_author_link(); comment_text();
}

add_filter('get_comments_number', 'firefly_get_comments_number', 0);
function firefly_get_comments_number() {
    // return comments number but not comments&pings number
    if (!is_admin()) {
        global $id;
        $comments_by_type = &separate_comments(get_comments('status=approve&post_id=' . $id));
        return count($comments_by_type['comment']);
    } //else
        //return get_comments_number();
}

function firefly_comments_number() {
    // print comments number but not comments&pings number
    $number = firefly_get_comments_number();
    switch ($number) {
        case 0:
            _e('No Comments', 'firefly');
            break;
        case 1:
            _e('One Comment', 'firefly');
            break;
        default:
            printf(__('%s Comments', 'firefly'), $number);
            break;
    }
}

function server2client_gate() {
    // make some info available from js
    printf('<script type="text/javascript">template_dir="%s"</script>', get_template_directory_uri() . '/');
    echo "\n";
}

function no_title($title) {
    // print <no title> for empty titles
    if ('' === $title) return __('&lt;No Title&gt;', 'firefly');
    else return $title;
}
add_filter('the_title', 'no_title');

function show_author() {
    // show or do not show post's author
    // return boolean
    $settings = get_theme_settings();
    return $settings['show_author'];
}

function show_ie_message() {
    // show or do not show warning message for IE6 and IE7
    $settings = get_theme_settings();
    return $settings['show_ie_message'];
}

function debug () {
    $settings = get_theme_settings();
    return $settings['debug'];
}

function copyright_years() {
    // Print years for copyright notice. It gets foundation year from
    // theme settings and minds about current year.
    $current_year = date('Y');
    $settings = get_theme_settings();
    if ($current_year == $settings['foundation_year'])
        echo $current_year;
    else
        echo "${settings['foundation_year']}–$current_year";
}

function copyright_name() {
    // print copyright name
    $settings = get_theme_settings();
    echo $settings['copyright_name'];
}

function firefly_version() {
    // print FireFly version (letter "v" and numbers)
    $settings = get_theme_settings();
    echo 'v'. $settings['firefly_version'];
}

load_theme_textdomain('firefly', get_template_directory() .'/languages');
add_action('init', 'firefly_init');
remove_action('wp_head', 'wp_generator');  // do not show Wordpress version for security reason
add_action('wp_head', 'server2client_gate');

?>